from django.forms import formset_factory, modelformset_factory, inlineformset_factory, BaseFormSet
from django import forms
from django.forms import ModelForm, Textarea
from blog.models import Author, Recipe, Ingredient
from django.utils.translation import gettext as _


class ProfileForm(forms.Form):
    first_name = forms.CharField(label='First Name', max_length=50, required=False)
    last_name = forms.CharField(label='Last Name', max_length=50, required=False)


class ArticleCreateForm:
    pass


class ArticleUpdateForm:
    pass


class ContactForm(forms.Form):
    name = forms.CharField(label='Your name', max_length=255)
    email = forms.EmailField(label='Email address')


class LoginForm(forms.Form):
    username = forms.CharField(
        required=True,
        max_length=20,
        min_length=6,
        error_messages={
            'required': '用户名不能为空',
            'max_length': '用户名长度不能超过20个字符',
            'min_length': '用户名长度不能少于6个字符',
        }
    )
    password = forms.CharField(
        required=True,
        max_length=20,
        min_length=6,
        error_messages={
            'required': '密码不能为空',
            'max_length': '密码长度不能超过20个字符',
            'min_length': '密码长度不能少于6个字符',
        }
    )


class AuthorForm(ModelForm):
    pass
    # class Meta:
    #     model = Author
    #     fields = ('name', 'title', 'birth_date')
    #     widgets = {
    #         'name': Textarea(attrs={'cols': 80, 'rows': 20}),
    #     }
    #     labels = {
    #         'name': _('Author'),
    #     }
    #     help_texts = {
    #         'name': _('Some useful help text.'),
    #     }
    #     error_messages = {
    #         'name': {
    #             'max_length': _("This writer's name is too long."),
    #         }
    #     }


class ContactForm1(forms.Form):
    name = forms.CharField(
        max_length=255,
        widget=forms.Textarea(
            attrs={'class': 'custom'},
        ),
    )


BIRTH_YEAR_CHOICES = ('1980', '1981', '1982')
COLORS_CHOICES = (
    ('blue', 'Blue'),
    ('green', 'Green'),
    ('black', 'Black'),
)


class SimpleForm(forms.Form):
    birth_year = forms.DateField(widget=forms.SelectDateWidget(years=BIRTH_YEAR_CHOICES))
    favorite_colors = forms.MultipleChoiceField(
        required=False,
        widget=forms.CheckboxSelectMultiple,
        choices=COLORS_CHOICES,
    )


class ArticleForm(forms.Form):
    pass


class BookForm(forms.Form):
    name = forms.CharField(max_length=100)
    title = forms.CharField(max_length=100)
    pub_date = forms.DateField(required=False)


# extra: 想要显示空表单的数量
# max_num: 表单显示的最大数量，可选，默认1000

BookFormSet = formset_factory(BookForm, extra=3, max_num=2)

# AuthorFormSet = modelformset_factory(
#     Author, form=AuthorForm, extra=3
# )


class RecipeForm(ModelForm):
    class Meta:
        model = Recipe
        fields = ('title', 'description')


IngredientFormSet = inlineformset_factory(Recipe, Ingredient, fields=('name',),
                                          extra=3, can_delete=False, max_num=5)


class BaseArticleFormSet(BaseFormSet):
    def clean(self):
        """

        :return:
        """
        if any(self.errors):
            return

        titles = []
        title = ''
        for form in self.forms:
            title = form.cleaned_data['title']
            if title in titles:
                raise forms.ValidationError('Article in a set must have distinct titles.')
        titles.append(title)

    def add_fields(self, form, index):
        super().add_fields(form, index)
        form.fields['my_field'] = forms.CharField()


ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet)
